//
//  SEHomeView.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/8.
//

import Foundation
import UIKit

class SEHomeView: UIView, PullToRefreshPresentable {
    let seTable = SEInspTableView()
    let headerV = SEHomeHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 500))

    var datas : [ParListModal?] = []

    var param = ParFormParam(type: "0", pageSize: PageSize)
    var pageNum: Int = 1
    var totalPage: Int64 = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupPullToRefresh(on: seTable.tableView)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NotiInsp, object: nil)

        setupUI()
        reloadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        seTable.tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        reloadData()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        fetchListData()
    }
    
    @objc func reloadData() {
        /// 巡检记录-服务工程师-数据统计
        API.getCountSelectCount { responseModel in
            DispatchQueue.main.async {
                self.headerV.updateUI(withModal: responseModel.model)
            }
        }
        
        fetchListData()
    }
    
    func fetchListData() {
        showToastActivity()
        param.pageNum = pageNum
        /// 维保服务-巡检记录
        API.getParFromList(withParam: param) { responseModel in
            if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                self.pageNum -= 1
                self.hideToastActivity()
                return
            }
            if self.pageNum == 1 {
                self.datas.removeAll()
            }
            self.totalPage = responseModel.totalPage
            self.datas.append(contentsOf: responseModel.models ?? [])
            DispatchQueue.main.async {
                self.seTable.datas =  self.datas
                self.hideToastActivity()
            }
        }
    }
   
    func setupUI() {
        seTable.emptyType = .seinsp
        seTable.needReload = { () -> () in
            self.param.pageNum = 1
            self.reloadData()
        }
        addSubview(seTable)
        seTable.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(-UIDevice.navigationFullHeight())
        }
        seTable.tableView.tableHeaderView = headerV
    }
}
